extends Node

var rand = RandomNumberGenerator.new()
var bomber: Spatial = preload("res://bomber.tscn").instance()
var envNode: ENV

func _ready():
	envNode = $"/root/sc/env"
	rand.randomize()

func _process(delta):
	pass

func _input(event: InputEvent):
	if event is InputEventMouseButton:
		var clickEvent = event as InputEventMouseButton
		if clickEvent.pressed: # 按下
			if clickEvent.button_index == BUTTON_LEFT:
				# 获取屏幕
				var screen = $'/root'
				
				var cameraNode: MeshInstance = envNode.cameraNode
				
				# 获取相机
				var camera: Camera = cameraNode.get_node("TrackballCamera")
				var r: Vector3 = camera.project_ray_normal(screen.size / 2)
				
				# 添加子弹
				createBomber(get_node("..").global_translation, r)

func createBomber(position: Vector3, to: Vector3):
	var sc = $"/root/sc/node"
	
	var bomberNew = bomber.duplicate()
	sc.add_child(bomberNew)
	
	var cubeNew = bomberNew.get_node("cube")
	cubeNew.translation = position
	cubeNew.linear_velocity = to * 30
	
	# 随机旋转
	cubeNew.rotate_x(rand.randf_range(0, 360))
	cubeNew.rotate_y(rand.randf_range(0, 360))
	cubeNew.rotate_z(rand.randf_range(0, 360))
	
	# 定时销毁
	yield(get_tree().create_timer(20), "timeout")
	sc.remove_child(cubeNew)
	cubeNew.queue_free()
